package com.sam.demo.service;

import com.sam.demo.config.DataSourceContextHolder;
import com.sam.demo.config.JpaDataSourceConfigCommon;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Order(-10)//保证该AOP在@Transactional之前执行
@Component
public class DynamicDataSourceAspect {

    @Pointcut("execution(* com.sam.demo.service..*.*(..))")
    private void aspect() {}

    @Around("aspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            DataSourceContextHolder.setDataSource(JpaDataSourceConfigCommon.SECONDAYR_DATASOURCE_KEY);
            return joinPoint.proceed();
        }finally {
            DataSourceContextHolder.clear();
        }
    }
}
